package SVN::TeamTools::Plugins::Search;

use warnings;
use strict;
use Carp;
use Error qw(:try);

use SVN::TeamTools::Store::Config;
use SVN::TeamTools::Store::SvnIndex;
use SVN::TeamTools::Store::Repo;
use SVN::TeamTools::Index::PrefixQuery;

use HTML::Template;
use CGI;
use URI::Escape;
use Data::Dumper;

my $conf;
my $logger;
BEGIN { $conf = SVN::TeamTools::Store::Config->new(); $logger = $conf->{logger}; }

sub hasAction {
	shift;
	my %args	= @_;
	my $action	= $args{action};
	return ("|dsp.search|get.search.result|" =~ /\|\Q$action\E\|/);
}

sub getTemplate {
	my $template = HTML::Template->new( filename => 'SVN/TeamTools/Plugins/tmpl/search.tmpl', path => @INC );
	my $rev = SVN::TeamTools::Store::Repo->new()->getSvnRev();
	$template->param (p_headrev => $rev);


	return $template;
}

sub getData {
	shift;
	my %args	= @_;
	my $param	= $args{param};

	my $svnindex = SVN::TeamTools::Store::SvnIndex->new(mode=>"r",create=>0);
	my $repo = SVN::TeamTools::Store::Repo->new();
	my @query;
	my @results;
	my $hits;

	if ($param->{sea_path}) {
		push (@query, $svnindex->getQuery (field=>"searchpath", term=>$param->{searchtext}));
	}
	if ($param->{sea_cont}) {
		push (@query, $svnindex->getQuery (field=>"content", term=>$param->{searchtext}));
	}
	if ($param->{sea_revlog} and $param->{src_basepath} eq "") {
		push (@query, $svnindex->getQuery (field=>"comments", term=>$param->{searchtext}));
	}

	if ($param->{src_basepath} eq "") {
		$hits = $svnindex->execORQuery (
				pagenum=>$param->{pagenum}, 
				pagesize=>$param->{pagesize}, 
				queries=>\@query
		);
	} else {
		my @andquery;
		push (@andquery, $svnindex->getORQuery (queries=>\@query));
		push (@andquery, $svnindex->getPrefixQuery (field=>"path", prefix=>$param->{src_basepath}));
		$hits = $svnindex->execANDQuery (
				pagenum=>$param->{pagenum}, 
				pagesize=>$param->{pagesize}, 
				queries=>\@andquery
		);
	}
		
	
	my @exthits;
	while ( my $hit = $hits->next()) {
		push (@exthits, $hit);

		if ($hit->{type} eq "doc") {
			my $links = $svnindex->linkSearch(path => $hit->{path});
			while (my $link = $links->next()) {
				push (@exthits, $link) unless ( $param->{src_basepath} ne "" and $link->{path} !~ m#^$param->{src_basepath}#);
			}
		}
	}

	foreach my $res (@exthits) {
		my $detail1 = ""; my $detail2 = "";
		my $uri;

		if ($res->{type} eq "rev") {
			$detail1 = $repo->getLook(rev => $res->{rev})->log_msg(); 
			$uri=$res->{rev};
		}
		if ($res->{type} eq "doc") {
			$detail1 = $res->{path}; 
			$uri=$res->{path};
		}
		if ($res->{type} eq "link") {
			$detail1 = $res->{path}; 
			$detail2 = 'Copied from: ' . $res->{cfpath}; 
			$uri=$res->{path};
		}
		my %obj = (
		    type      => $res->{type},
		    committer => $res->{author},
		    path      => $res->{path},
		    detail1   => $detail1,
		    detail2   => $detail2,
		    rev       => $res->{rev}
		);
		push( @results, \%obj );
	}
	return {
		hits	=> $hits->total_hits,
		result	=> \@results,
	};	
}
1;
